package com.cedifie.lendapp.ui.steps.impl

import android.content.Context
import com.cedifie.lendapp.MyApplication
import com.cedifie.lendapp.R
import com.cedifie.lendapp.http.IHttpCallback
import com.cedifie.lendapp.mvp.presenter.MvpPresenter
import com.cedifie.lendapp.ui.steps.view.ICedAccountView
import com.cedifie.lendapp.utils.helper.SharedHelper
import org.json.JSONObject

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/17 13:45
 * @Annotation：绑卡 Presenter 实现
 */
class CedAccountPresenterImpl(context: Context?) : MvpPresenter<ICedAccountView>(context) {
    private var model: CedAccountModelImpl? = null

    init {
        model = CedAccountModelImpl()
    }

    /**
     * 获取已绑定的账户列表
     */
    fun loadCedAccountListAction(){
        model?.loadCedAccountListAction(object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val array = data.optJSONArray("obj")
                        val accountList = arrayListOf<JSONObject>()

                        if (array != null && array.length() > 0) {
                            for (i in 0..<array.length()) {
                                val item = array.optJSONObject(i)
                                item.put("isEdit", false)
                                accountList.add(item)
                            }
                        }

                        if (accountList.size < 2) {
                            for (i in 0..<2 - accountList.size) {
                                val item = JSONObject()
                                item.put("isEdit", true)
                                accountList.add(item)
                            }
                        }
                        mvpView?.showCedAccountList(accountList)

                        //提交按钮是否可点
                        var submitIsEnabled = false
                        for (i in 0..<accountList.size){
                            //存在一个不是编辑状态的item，则可以提交
                            if (!accountList[i].optBoolean("isEdit",true)){
                                submitIsEnabled = true
                                break
                            }
                        }
                        mvpView?.showCedSubmitButton(submitIsEnabled)
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showCedToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showCedToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideCedLoading()
            }
        })
    }

    /**
     * 添加绑卡
     */
    fun submitCedBindAccountAction(mobile: String, walletChannel: String, bindFlag:String = "NO"){
        mvpView?.showCedLoading(MyApplication.app.getString(R.string.loading))
        model?.submitCedBindAccountAction(mobile,walletChannel,bindFlag,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                //刷新列表
                loadCedAccountListAction()
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj") ?: JSONObject()

                        // "YES/NO 是否需要提示用户这个号码可以绑另一个渠道的钱包"
                        val addBindFlag = obj.optString("addBindFlag")
                        if (addBindFlag == "YES") {
                            //需要提示绑定另一个渠道账户
                            var otherAccountInfo: JSONObject? = null

                            //用于从APP配置中获取（walletChannels）对应的信息
                            val channel = obj.optString("channel")
                            if (channel.isNotBlank()) {
                                val spData = SharedHelper.getCedSPString(SharedHelper.CED_SPKEY.CEDIFIE_COMMON)
                                if (spData.isEmpty()){
                                    return
                                }
                                val commonData = JSONObject(spData)
                                val customize = commonData.optJSONObject("customize")
                                if (customize != null) {
                                    val walletChannels = customize.optJSONArray("walletChannels")
                                    if (walletChannels != null && walletChannels.length() > 0) {
                                        for (i in 0..<walletChannels.length()) {
                                            val item = walletChannels.optJSONObject(i)
                                            if (channel == item.optString("value")) {
                                                otherAccountInfo = item
                                                break
                                            }
                                        }
                                    }

                                    // 只有非空的情况下才处理
                                    if (otherAccountInfo != null) {
                                        otherAccountInfo.put("walletMobile", mobile)
                                        //提示绑定另一个渠道账户
                                        mvpView?.showCedBingAccountOtherDialog(otherAccountInfo)
                                        return
                                    }
                                }
                            }
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showCedToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showCedToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideCedLoading()
            }
        })
    }

    /**
     * 删除账户
     */
    fun deleteCedAccountAction(ids: String) {
        mvpView?.showCedLoading(MyApplication.app.getString(R.string.loading))
        model?.deleteCedAccountAction(ids,object: IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                mvpView?.showCedToast(data.optString("msg"))
                when(data.optInt("code")) {
                    0 -> {//成功
                        //刷新列表
                        loadCedAccountListAction()
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showCedToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showCedToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideCedLoading()
            }
        })
    }
}